package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.util.List;


@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");

        if ("list".equals(operation)){
            this.list(req,resp);
        }else if ("toAdd".equals(operation)){
            this.toadd(req,resp);
        }else if ("save".equals(operation)){
            try {
                this.save(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("toEdit".equals(operation)){
            this.toEdit(req,resp);
        }else if("delete".equals(operation)){
            this.delete(req,resp);
        }else if("edit".equals(operation)){
            try {
                this.edit(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("toTestUpload".equals(operation)){
            this.toTestUpload(req,resp);
        }else if("testUpload".equals(operation)){
            try {
                this.testUpload(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("toExport".equals(operation)){
            this.toExport(req,resp);
        }
    }

    private void toExport(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");;

        String fileName = new String("我的测试题目.xlsx".getBytes(),"iso8859-1");

        resp.addHeader("Content-Disposition","attachment;fileName="+fileName);


        ByteArrayOutputStream os = questionService.getReport();

        ServletOutputStream sos = resp.getOutputStream();

        os.writeTo(sos);
        sos.flush();
        os.close();
    }

    private void toTestUpload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(request,response);
    }

    private void testUpload(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);

            List<FileItem> fileItems = fileUpload.parseRequest(req);

            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),fileItem.getName()));
                }
            }
        }

    }


    private void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        if(ServletFileUpload.isMultipartContent(req)){
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);

            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //创建一个标记位,标记当前时候有上传文件的操作
            boolean flag = false;
            for(FileItem item :fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }

            Question question = BeanUtil.fillBean(fileItems, Question.class);

            questionService.update(question,flag);

            for (FileItem item: fileItems){
                if (!item.isFormField()){
                    item.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
                }
            }
            //跳转回到页面list
            resp.sendRedirect(req.getContextPath()+"/store/question?operation=list");
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将数据获取到，封装成一个对象
        Question question = BeanUtil.fillBean(req,Question.class);
        //调用业务层接口save
        questionService.delete(question);
        //跳转回到页面list
        resp.sendRedirect(req.getContextPath()+"/store/question?operation=list");
    }
    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Question question = questionService.findById(id);

        req.setAttribute("question",question);

        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();

        req.setAttribute("companyList",companyList);
        req.setAttribute("catalogList",companyList);

        req.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(req,resp);
    }


    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        if(ServletFileUpload.isMultipartContent(req)){
            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload fileUpload = new ServletFileUpload(factory);

            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //创建一个标记位,标记当前时候有上传文件的操作
            boolean flag = false;
            for(FileItem item :fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }

            Question question = BeanUtil.fillBean(fileItems, Question.class);

            String save = questionService.save(question,flag);

            // --处理form表单提交过来的文件数据
            for(FileItem item : fileItems){
                //5.当前表单是否是文件表单
                if(!item.isFormField()){
                    //6.从临时存储文件的地方将内容写入到指定位置
                    item.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
                }
            }
        }
        resp.sendRedirect(req.getContextPath()+"/store/question?operation=list");
    }


    private void toadd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();

        req.setAttribute("companyList",companyList);

        req.setAttribute("catalogList",catalogList);

        req.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(req,resp);

    }
    private void list(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        int page = 1;
        int size = 5;

        if (StringUtils.isNotBlank(req.getParameter("page"))){
            page = Integer.parseInt(req.getParameter("page"));
        }
        if (StringUtils.isNotBlank(req.getParameter("size"))){
            size = Integer.parseInt(req.getParameter("size"));
        }

        PageInfo all = questionService.findAll(page,size);

        req.setAttribute("page",all);

        req.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(req,resp);

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
